package com.cspm.ahjy.bc.office.word.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Element;
import org.springframework.util.StringUtils;

import com.cspm.ahjy.bc.office.word.domain.MSTableCol;
import com.cspm.ahjy.bc.office.word.domain.MSTableRow;

/**
 * 表格行工具
 * @author ServerZhang
 * @date 2017年10月12日
 */
public class TableRowUtil {

	/**
	 * 解析<w:tr>标签
	 * @param trElement
	 * @param path 文档所在目录 
	 * @return
	 * @author ServerZhang
	 * @date 2017年10月12日
	 */
	public static MSTableRow getMsTableRow(Element trElement, String path){
		MSTableRow msTableRow = new MSTableRow();
		
		if (trElement == null) {
			return msTableRow;
		}
		
		//1.行属性
		Element trPr = trElement.element("trPr");
		if (trPr != null) {
			Element trHeight = trPr.element("trHeight");
			if (trHeight != null) {
				Attribute rule = trHeight.attribute("h-rule");
				Attribute val = trHeight.attribute("val");
				if (rule != null) {
					msTableRow.setHeightRule(rule.getText());
				}else {
					msTableRow.setHeightRule("smallest");
				}
				if(val != null){
					msTableRow.setHeight(Integer.parseInt(val.getText()));
				}
			}
		}
		//2.获取列
		List<Element> tcList = trElement.elements("tc");
		Iterator<Element> iterator = tcList.iterator();
		List<MSTableCol> msCols = new ArrayList<MSTableCol>();
		
		String alignType = null;
		String horizontalType = null;
		
		int index = 0;
		while(iterator.hasNext()){
			Element next = iterator.next();
			MSTableCol msTableCol = TableColUtil.getMSTableCol(next,path);
			msCols.add(msTableCol);
			
			String text = msTableCol.getText();
			if (StringUtils.isEmpty(text)) {
				continue;
			}
			
			if (index == 0) {
				alignType = msTableCol.getAlignType();
			}else if (alignType != null) {
				if (!alignType.equals(msTableCol.getAlignType())) {
					alignType = null;
				}
			}
			if (index == 0) {
				horizontalType = msTableCol.getHorizontalType();
			}else if (horizontalType != null) {
				if (!horizontalType.equals(msTableCol.getHorizontalType())) {
					horizontalType = null;
				}
			}
			index ++;
		}
		msTableRow.setMsTableCols(msCols);
		msTableRow.setAlignType(alignType);
		msTableRow.setHorizontalType(horizontalType);
		
		return msTableRow;
	}
}
